package com.cms.service.impl;
 
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cms.common.StringUtils;
import com.cms.constant.CacheConstant;
import com.cms.dao.mapper.SystemConfigMapper;
import com.cms.model.TrSystemConfig;
import com.cms.redis.RedisService;
import com.cms.service.MemberUserService;
import com.cms.service.SystemConfigService;
import com.google.common.collect.Maps;

@Service
public class SystemConfigServiceImpl implements SystemConfigService {
	
	private static Logger logger =LoggerFactory.getLogger(SystemConfigService.class);

	@Autowired
	private SystemConfigMapper configMapper;

	@Autowired
	private MemberUserService memberService;

	@Override
	public List<TrSystemConfig> querySystemConfig() {
		return configMapper.querySystemConfig();
	}

	@Override
	public void updateSystemConfig(List<TrSystemConfig> configs) throws Exception {
		configMapper.updateSystemConfig(configs);
		this.updateReportCache(configs);
	}

	/***
	 * 
	 * @param configs
	 */
	private void updateReportCache(List<TrSystemConfig> configs) throws Exception {
		Map<String, String> result =Maps.newHashMap();
		if (configs != null && !configs.isEmpty()) {
			configs.parallelStream().forEach(config -> {
				if (StringUtils.equals(config.getName(), CacheConstant.CLOSING_SWITCH)) {
					// 网站关闭
					if (StringUtils.equals(config.getValue(), CacheConstant.CLOSING_SWITCH_OFF)) {
						RedisService.getRedisService().flushDB(2);
						try {
							this.memberService.setUserOffline();
						} catch (Exception e) {
							logger.error("updateReportCache.error:{}",ExceptionUtils.getStackFrames(e));
						}
					}
				}
				result.put(config.getName(), config.getValue());
			});
			RedisService.getRedisService().hmset(CacheConstant.CMS_CONF_KEY, result);
		}
	}
}
